package com.ly.datacenter.component.pager.pojo;
/**
 * function：
 * @author watson  email: watson.wu@hotmail.com
 * @date 2009-9-7
 */
public class MsSQLPagination {

	private static final String ORDER_BY = "order by";
	public static final String FROM = "from";
	public static final String WHERE = "where";
	public static final String SELECT = "select";
	
	public static String getPaginationSql(String sql, int page, int pagesize) {
		//TODO
		return sql;
	}

	/**
	 * function:&lt;just for the pk in order&gt;
	 * @param sql
	 * @param page
	 * @param pagesize
	 * @param totalsize
	 * @param pk
	 * @return
	 */
	public static String getPaginationSql(String sql, int page, int pagesize, int totalsize, String pk) {
		StringBuffer pagingQuery = new StringBuffer();
		StringBuffer sb = new StringBuffer(sql.toLowerCase());
		int startIndex = (page-1) * pagesize+1;
		int endIndex = page * pagesize-1;
		pagingQuery.append("select * from(select top").append(pagesize).append(" * from(");
		boolean asc = startIndex>(totalsize-startIndex);
		if(asc) {
			sb.replace(sb.indexOf(SELECT), sb.indexOf(SELECT)+SELECT.length()+1, "select top"+endIndex);
			if(sql.contains(ORDER_BY)){
				int indexOfWhere = sql.lastIndexOf(WHERE);
				if(sb.lastIndexOf("having", indexOfWhere)>0 || sb.lastIndexOf("max", indexOfWhere)>0 || sb.lastIndexOf("mix", indexOfWhere)>0){
					StringBuffer temp = new StringBuffer(sql);
					temp.replace(temp.indexOf(SELECT), temp.indexOf(FROM), "select top "+(startIndex-1)+" "+pk+" ");
					sb.replace(sb.indexOf(WHERE), sb.indexOf(WHERE)+WHERE.length()+1, "where "+pk+" not int("+temp+")");
				}else{
					
				}
			}else{
				
			}
			
		} else {
			
		}
		return pagingQuery.toString();
	}

}